package com.example.ucs_alg_node_manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ucs_alg_node_manager.domain.User;
import com.example.ucs_alg_node_manager.dto.LoginDTO;
import com.example.ucs_alg_node_manager.mapper.UserMapper;
import com.example.ucs_alg_node_manager.service.UserService;
import com.example.ucs_alg_node_manager.utils.EmailUtil;
import com.example.ucs_alg_node_manager.utils.JwtUtil;
import com.example.ucs_alg_node_manager.utils.RandomUtil;
import com.example.ucs_alg_node_manager.vo.ReturnVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
* @author 31586
* @description 针对表【ucs_user】的数据库操作Service实现
* @createDate 2024-08-29 16:05:15
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private EmailUtil emailUtil;

    @Override
    public ReturnVO login(LoginDTO loginDTO) {
        String account = loginDTO.getAccount();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account);

        if (userMapper.selectOne(wrapper)==null) {
            return ReturnVO.fail().message("登录失败，用户信息不存在");
        }
        String passwd = loginDTO.getPasswd();
        wrapper.eq(User::getPasswd,passwd);
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            return ReturnVO.fail().message("登录失败，密码错误");
        }
        user.setToken(JwtUtil.createToken(user.getId()));
        return ReturnVO.ok(user).message("登陆成功");
    }

    @Override
    public ReturnVO reset(String email) {
        if(!"@qq.com".equals(email.substring(email.length()-7, email.length()))){
            return ReturnVO.fail().message("错误qq邮箱格式");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        User user = userMapper.selectOne(wrapper);
        if(user==null) {
            return ReturnVO.fail().message("邮箱信息不存在");
        }
        String passwd = RandomUtil.getPasswd();
        user.setPasswd(passwd);
        updateById(user);
        emailUtil.sendEmail(email, user.getAccount(), passwd);
        return ReturnVO.ok().message("密码重置成功，请前往邮箱查看");
    }
}




